package fnic.prehand.augment.resource;

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;

public class DBResource {
	
	private static DBResource resource = new DBResource();
	
	private Map<String ,DBPool> dbs;
	
	private  DBResource() {
		init();
	}
	
	public static DBResource getInstance(){
		return resource;
	}

	@SuppressWarnings("unchecked")
	private void init() {
		//通过XML文件来获取数据库相关配置
		dbs = new HashMap<String, DBPool>(8);
		XStream x = new XStream(new StaxDriver());
		x.alias("pools", ArrayList.class);
		x.alias("DBPool", DBPool.class);
		List<DBPool> list =   (List<DBPool>) x.fromXML(new File("config/database.xml"));
		for(DBPool t : list){
			t.init();
			dbs.put(t.name, t);
		}
	}
	
	public Connection getConnection(String name) throws SQLException{
		if(dbs.get(name) != null)
			return dbs.get(name).getConnection();
		return null;
	}
	
	public Connection getConnection() throws SQLException{
		return getConnection("default");
	}
}
